<template>

  <div class="divBox">


    <el-card class="box-card">
      <div slot="header" class="clearfix">

        <div class="container">
          <div class="demo-input-suffix acea-row">
            <el-form inline size="small" label-width="100px" :model="productFrom" ref="productFrom">
              <el-row>
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                  <el-col>
                    <el-form-item label="阿里巴巴类目：" prop="cate_ids">
                      <el-cascader v-model="productFrom.cate_ids" :props="cascaderProps" class="selWidth"
                                   @change="getProductListApi('1',true)"/>
                    </el-form-item>

                  </el-col>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                  <el-col>
                    <el-form-item label="选品ID：" prop="cate_id">
                      <el-input v-model="productFrom.cate_id" placeholder="请输入选品ID" clearable class="selWidth"/>
                    </el-form-item>

                  </el-col>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                  <el-col>
                    <el-form-item label="价格区间开始：" prop="price_start">
                      <el-input v-model="productFrom.price_start" placeholder="请输入价格区间开始" clearable type="number"
                                class="selWidth"/>
                    </el-form-item>
                    <el-form-item label="价格区间结束：" prop="price_end">
                      <el-input v-model="productFrom.price_end" placeholder="请输入价格区间结束" clearable type="number"
                                class="selWidth"/>
                    </el-form-item>
                  </el-col>
                </el-col>
                <el-form-item label="关键词：" prop="keyword">
                  <el-input v-model="productFrom.keyword" @keyup.enter.native="getProductListApi('',true)"
                            placeholder="请输入关键词" class="selWidth" clearable>
                    <el-button slot="append" icon="el-icon-search" class="el-button-solt"
                               @click="getProductListApi('',true)"/>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" @click="batch(productList)">批量采集</el-button>
                  <el-button size="mini" @click="reset('productFrom')">重置</el-button>
                </el-form-item>
              </el-row>

            </el-form>
          </div>
        </div>

      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="productList"
        style="width: 100%"
        size="small"
        @selection-change="handleSelectionChange"
        row-key="store_category_id"
        :default-expand-all="false"
      >
        <el-table-column key="2" type="selection" width="55" :selectable="checkboxSelect"/>

        <el-table-column label="商品图片" min-width="150" prop="imgUrl" align="center">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 80px; height: 80px"
                :src="scope.row.imgUrl?scope.row.imgUrl:moren"
                :preview-src-list="images"
                @click="getProductInfo(scope.row.itemId,false)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="商品标题"
          min-width="200"
          prop="title"
        >
          <template slot-scope="scope">
            <span >{{ scope.row.title }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="itemId"
          label="商品id"
          min-width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.itemId }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="minPrice"
          label="最小价格（元）"
          min-width="110"
          sortable
          :sort-method="(a,b)=>{return a.minPrice - b.minPrice}"
        >
          <template slot-scope="scope">
            <span>{{ getMoney(scope.row.minPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="maxPrice"
          label="最大价格（元）"
          min-width="110"
          sortable
          :sort-method="(a,b)=>{return a.maxPrice - b.maxPrice}"
        >
          <template slot-scope="scope">
            <span>{{ getMoney(scope.row.maxPrice) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="salesCnt90d"
          label="90天销量"
          min-width="100"
          sortable
          :sort-method="(a,b)=>{return a.salesCnt90d - b.salesCnt90d}"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.salesCnt90d }}</span>
          </template>

        </el-table-column>

        <el-table-column
          prop="isGather"
          label="是否采集"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isGather"
              :active-value="true"
              :inactive-value="false"
              active-text="已采"
              inactive-text="未采"
              inactive-color="#c8cad1"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="getProductInfo(scope.row.itemId,true)">详情</el-button>
            <el-button type="text" size="small" @click="onEdit(scope.row.itemId)" v-if="!scope.row.isGather">采集
            </el-button>
            <el-button type="text" size="small" v-else disabled>采集
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination :page-sizes="[15, 30, 45, 50]" :page-size="pageInfo.pageSize"
                       ref="Pagination"
                       :current-page.sync="isChange?pageInfo.currentPage:productFrom.page"
                       layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.totalRecords"
                       @size-change="handleSizeChange" @current-change="pageChange"/>
      </div>

    </el-card>
    <el-dialog title="商品详情" :visible.sync="dialogVisible" width="1000px" :before-close="handleClose"
               :append-to-body='append'>
      <div>
        <div class="item">
          <span style="font-size: 16px">商品名称：</span>
          <span style="font-size: 14px">{{ productDetail.subject }}</span>
        </div>

        <div class="item mt10">
          <span style="font-size: 16px">商品货号：</span>
          <span style="font-size: 14px">{{ productDetail.cargoNum }}</span>
        </div>

        <div class="item mt10">
          <span style="font-size: 16px">成交量：</span>
          <span style="font-size: 14px">{{ productDetail.bookedCount }}</span>
        </div>
        <div class="item mt10">
          <span style="font-size: 16px">参考价格：</span>
          <span style="font-size: 14px">{{ productDetail.referencePrice }}（元）</span>
        </div>
        <div class="item mt10">
          <span style="font-size: 16px">类目ID：</span>
          <span style="font-size: 14px">{{ productDetail.categoryID }}</span>
        </div>
        <div class="item mt10">
          <span style="font-size: 16px">类目名：</span>
          <span style="font-size: 14px">{{ productDetail.categoryName }}</span>
        </div>
        <div class="mt20" v-html="productDetail.description"></div>
<!--        <ueditor-from class="mt20" v-model="productDetail.description" :content="productDetail.description"/>-->
      </div>
    </el-dialog>
    <!--编辑标签-->
    <el-dialog
      v-if="dialogLabel"
      title="设置价格"
      :visible.sync="dialogLabel"
      width="800px"
      :before-close="handleClose"
    >
      <el-form :model="money" @submit.native.prevent>
        <el-form-item label="请设置价格：">
          <el-input v-model="money" placeholder="请输入价格" clearable
                    class="selWidth"/>
          <span style="font-size: 16px">（分）</span>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {
  storeCategoryCreateApi,
  storeCategoryDeleteApi,
  storeCategoryStatusApi,
  storeCategoryRecommendApi,
  cateListApi,
  productListApi,
  productGatherApi,
  productInfoApi,
} from '@/api/product'
import {roterPre} from '@/settings'
import ueditorFrom from "@/components/ueditorFrom/index.vue";
import {forEach} from "../../../../../public/UEditor/third-party/xss.min";

export default {
  name: 'GatherAlibaba',
  components: {ueditorFrom},

  data() {

    return {
      productFrom: {
        cate_ids: [],
        page: 1,
        size: 45,
        cate_id: '',
        name: '',
        keyword: '',
        price_start: '',
        price_end: ''
      },
      isChange: false,//是否需要重置页码的开关
      money: '',
      append: true,
      dialogVisible: false,
      roterPre: roterPre,
      productInfo: {
        product_id: ''
      },
      dialogLabel: false,
      productDetail: {},
      merCateList: [],
      value: [],
      multipleSelection: [],
      object: {product_ids: []},
      productList: [],
      moren: require("@/assets/images/bjt.png"),
      isChecked: false,
      listLoading: true,
      tableData: {
        data: [],
        total: 0
      },
      images: [],
      // 商品多级分类
      cascaderProps: {
        emitPath: true,
        lazy: true, // 开启懒加载
        checkStrictly: true, //可选择任意节点
        lazyLoad: this.getCateList
      },
      pageInfo: {
        currentPage: 1
      },
      tableFrom: {
        page: 1,
        limit: 20
      },
      cateFrom: {
        cate_id: 0
      }

    }
  },
  mounted() {
    this.getProductListApi('', true)
  },
  methods: {
    rowClass({row, rowIndex}) {
      return 'background:#F3F4F7;color:#555'
    },

    //1688商品列表
    getProductListApi(num, isChange) {
      this.listLoading = true
      this.isChange = isChange
      if (isChange) {
        //重置分页页码为1
        this.productFrom.page = 1
      } else {
        if(num===-1){
          this.productFrom.page=this.productFrom.page+1
        }else{
          this.productFrom.page = num ? num : this.productFrom.page;
        }
      }
      if (this.productFrom.cate_ids.length > 0) {
        this.productFrom.cate_id = this.productFrom.cate_ids[this.productFrom.cate_ids.length - 1]
      }
      console.log(this.productFrom)
      productListApi(this.productFrom).then(res => {
        this.productList = res.data.result
        this.pageInfo = res.data.pageInfo
        this.listLoading = false
        console.log(res.data)
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    //1688商品采集-批量
    productGather(rows) {
      this.listLoading = true
      console.log(this.object)
      productGatherApi(this.object).then(res => {
        this.listLoading = false
        this.$message.success(res.message)
        if (rows) {
          rows.forEach(row => {
            if (!row.isGather) {
              row.isGather = true
            }
          });
          this.$refs.multipleTable.clearSelection();
        }
        this.getProductListApi(-1, false)
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    //1688商品采集-单独
    productGatherAlone(product_id) {
      this.listLoading = true
      const data = []
      data.push(product_id)
      this.object.product_ids = data
      console.log(this.object)
      productGatherApi(this.object).then(res => {
        this.listLoading = false
        this.$message.success(res.message)
        this.getProductListApi(this.productFrom.page, false)
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    //1688商品详情
    getProductInfo(product_id, isShow) {
      this.images = []
      this.dialogVisible = isShow
      this.productInfo.product_id = product_id
      productInfoApi(this.productInfo).then(res => {
        this.productDetail = res.data
        if (!isShow) {
          res.data.image.images.forEach((item) => {
            this.images.push('https://cbu01.alicdn.com/' + item)
          })
        }
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    //1688商品类目列表
    getCateList(node, resolve) {
      const nodes = [];
      if (node.hasChildren || node.root) {
        setTimeout(() => {
          // 构造查询条件
          let query = {
            cate_id: node.value,
            level: node.level + 1
          }
          //查询接口
          cateListApi(query).then(res => {
            let list = []
            list = res.data
            this.merCateList = list[0].childCategorys
            this.merCateList.map((item) => {
              let obj = {
                value: item.id,
                label: item.name,
                leaf: item.isLeaf // 节点级别，如果没有子节点就停止查询
              }
              nodes.push(obj);
            })
            //重新加载节点
            resolve(nodes);
          })
        }, 100);
      } else {
        //如果没有子节点就不发起请求，直接渲染，也避免了点击叶子节点仍然有加载动画的问题
        resolve(nodes);
      }

    },
    //重置
    reset(formName) {
      this.$refs[formName].resetFields();
      this.getProductListApi('', true)
    },

    // 设置价格
    onEditMoney() {
      this.dialogLabel = true
    },
    //已采集的商品防止重复采集
    checkboxSelect(row) {
      if (row.isGather) {
        return false
      } else {
        return true
      }
    },
    submitForm() {
      console.log(this.money)
      this.dialogLabel = false
    },
    handleClose() {
      this.dialogVisible = false
      this.dialogLabel = false
    },
    pageChange(page) {
      this.productFrom.page = page
      this.getProductListApi('', false)
    },
    handleSizeChange(val) {
      this.productFrom.size = val
      this.getProductListApi('', true)
    },
    // 添加
    onAdd() {
      this.$modalForm(storeCategoryCreateApi()).then(() => this.getList())
    },
    // 采集
    onEdit(product_id) {
      this.productGatherAlone(product_id)
    },
    batch(rows) {
      if (this.multipleSelection.length === 0) {
        if (rows) {
          rows.forEach(row => {
            if (!row.isGather) {
              this.$refs.multipleTable.toggleRowSelection(row);
            }
          });
        }
      }
      this.modalSure(`确定采集这${this.multipleSelection.length}件商品吗`).then(() => {
          this.productGather(rows)
        }
      )

    },
    modalSure(title) {
      return new Promise((resolve, reject) => {
        this.$confirm(`${title || '删除该文件吗'}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resolve()
        }).catch(action => {
          this.$refs.multipleTable.clearSelection();
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      })
    },
    //单位换算 分-元
    getMoney(money) {
      let number = money / 100
      return number.toFixed(2);
    },
    // 删除
    handleDelete(id, idx) {
      this.$modalSure().then(() => {
        storeCategoryDeleteApi(id).then(({message}) => {
          this.$message.success(message)
          this.getList()
        }).catch(({message}) => {
          this.$message.error(message)
        })
      })
    },
    onchangeIsShow(row) {
      storeCategoryStatusApi(row.store_category_id, row.is_show).then(({message}) => {
        this.$message.success(message)
      }).catch(({message}) => {
        this.$message.error(message)
      })
    },
    onchangeIsRecommend(row) {
      storeCategoryRecommendApi(row.store_category_id, row.is_hot).then(({message}) => {
        this.$message.success(message)
      }).catch(({message}) => {
        this.$message.error(message)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      const data = []
      this.multipleSelection.map((item) => {
        data.push(item.itemId)
      })
      this.object.product_ids = data
    },
  }
}
</script>

<style scoped lang="scss">

.item {
  display: flex;
  flex-direction: row;
}

.mt10 {
  margin-top: 10px;
}
</style>
